import queryParams from '@/utils/queryParams'
import test from '@/utils/test'

// 跳转去webview
export function navToWebView(path, params = {}) {
  const url = path + queryParams(params)
  // #ifdef H5
  location.href = url
  // #endif
  // #ifndef H5
  let query = {
    url,
  }
  if (url.includes('?')) {
    const arr = url.split('?')
    query = arr[1].split('&').reduce((pre, curr) => {
      const arr = curr.split('=')
      pre[arr[0]] = arr[1]
      return pre
    }, {})
    query.url = arr[0]
  }
  navTo('/pages/web-view/index', query)
  // #endif
}

export const handleFileUpload = (filePath, callback) => {
  const baseUrl = '/api/frontapi/common/file/add'
  let url = `${getApp().globalData.VUE_APP_API_URL}${baseUrl}`
  //#ifdef H5
  if (process.env.NODE_ENV === 'development') {
    url = `/api${baseUrl}`
  } else {
    url = `${baseUrl}`
  }
  //#endif
  uni.showLoading({
    title: '上传图片中...',
    mask: true,
  })
  uni.uploadFile({
    url,
    name: 'file',
    filePath,
    formData: {},
    header: {},
    success: (res) => {
      let data = test.jsonString(res.data) ? JSON.parse(res.data) : res.data
      if (data.code !== '0') {
        uni.hideLoading()
        return
      }
      callback(data.data)
    },
    complete: () => {
      uni.hideLoading()
    },
  })
}

// 跳转去拍照
export function navToPhotograph(pageType) {
  const handleChooseImage = (callback) => {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: function (res) {
        callback(res.tempFilePaths[0])
      },
    })
  }

  handleChooseImage((filePath) => {
    handleFileUpload(filePath, (res) => {
      navTo('/pages/search/img-result', {
        filePath: res.filePath,
        pageType,
      })
    })
  })
}

// 跳转
export default function navTo(path, params = {}, arrayFormat = 'comma', type = 'navigateTo') {
  const tabList = [
    {
      pagePath: '/pages/main/index',
    },
    {
      pagePath: '/pages/main/list',
    },
    {
      pagePath: '/pages/main/profile',
    },
  ]
  const isTab = tabList.map((x) => x.pagePath).includes(path)
  if (isTab) {
    if (path === '/pages/my-sobot/index') {
      uni.navigateTo({
        //#ifdef H5
        url: '/my-sobot/index',
        //#endif
        //#ifndef H5
        url: path,
        //#endif
      })
      return
    }

    uni.switchTab({
      url: path,
    })
  } else {
    if (!path) {
      !params.noToast &&
        uni.showToast({
          title: '页面正在开发中...',
          icon: 'none',
        })
      return
    }

    let toPath = path

    //#ifdef H5
    const routerPathMap = ROUTES.reduce((prev, item) => {
      prev[item.path] = item
      return prev
    }, {})
    // 路由转换完毕，需要根据aliasPath跳转
    const router = routerPathMap[path]
    toPath = router.aliasPath
    //#endif

    uni[type]({
      url: toPath + queryParams(params, true, arrayFormat),
    })
  }
}
